package com.zbkj.crmeb.supplier.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.crmeb.chant.dao.ChannelMerchantDao;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.request.MerchantListRequest;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.enums.ShopProductSelectTypeEnum;
import com.zbkj.crmeb.enums.SupplierTypeEnum;
import com.zbkj.crmeb.enums.WineryShippingTypeEnum;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.merchant.admin.service.SupplierStoreProductService;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.SupplierOpenShopRequest;
import com.zbkj.crmeb.store.request.SupplierStoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.SupplierInfo;
import com.zbkj.crmeb.store.response.SupplierOpenShopResponse;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.supplier.dao.BusinessApplyDao;
import com.zbkj.crmeb.supplier.dao.SupplierOpenShopDao;
import com.zbkj.crmeb.supplier.dao.SupplierOpenShopProductDao;
import com.zbkj.crmeb.supplier.model.BusinessApply;
import com.zbkj.crmeb.supplier.model.SupplierOpenShop;
import com.zbkj.crmeb.supplier.model.SupplierOpenShopProduct;
import com.zbkj.crmeb.supplier.service.BusinessApplyService;
import com.zbkj.crmeb.supplier.service.SupplierOpenShopProductService;
import com.zbkj.crmeb.supplier.service.SupplierOpenShopService;
import com.zbkj.crmeb.user.service.UserService;


@Service("supplierOpenShopService")
public class SupplierOpenShopServiceImpl extends ServiceImpl<SupplierOpenShopDao, SupplierOpenShop> implements SupplierOpenShopService {

    @Resource
    private SupplierOpenShopDao supplierOpenShopDao;

    @Resource
    private BusinessApplyService businessApplyService;

    @Resource
    private BusinessApplyDao businessApplyDao;

    @Resource
    private ChannelMerchantDao channelMerchantDao;

    @Resource
    private UserService userService;

    @Resource
    private StoreProductService storeProductService;

    @Resource
    private SupplierOpenShopProductService supplierOpenShopProductService;

    @Resource
    private SupplierStoreProductService supplierStoreProductService;

    @Autowired
    private MerProductService productService;

    @Resource
    private SupplierOpenShopProductDao supplierOpenShopProductDao;

    @Autowired
    private IChannelMerchantService channelMerchantService;

    private static final Logger logger = LoggerFactory.getLogger(SupplierOpenShopServiceImpl.class);

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<SupplierOpenShopResponse> getList(SupplierOpenShopRequest request, PageParamRequest pageParamRequest, Integer merId) {
        //条件查询
        SupplierInfo supplierInfo = null;
        try {
            supplierInfo = channelMerchantService.getSupplierInfo(merId);
        }catch (Exception e){
            logger.error("获取渠道商信息异常！");
        }
        if(null != supplierInfo){
            request.setSupplierId(supplierInfo.getSupplierId());
        }else {
            logger.error("渠道商不存在，merId:{}", merId);
        }
        MerchantListRequest merchantListRequest = new MerchantListRequest();
        merchantListRequest.setNotChannelType(3);
        merchantListRequest.setPage(1);
        merchantListRequest.setLimit(9999);
        PageInfo<ChannelMerchantVO>  channelMerchantVOPageInfo = channelMerchantService.merchantListV2(merchantListRequest, false);
        List<ChannelMerchantVO> channelMerchantList = channelMerchantVOPageInfo.getList();
        Map<Integer, String> channelMerchantMap = channelMerchantList.stream().collect(Collectors.toMap(ChannelMerchantVO::getId, ChannelMerchantVO::getChannelName, (e1, e2) -> e2));

        BusinessApply businessApply = businessApplyService.getById(supplierInfo.getApplyId());

        Page<SupplierOpenShop> supplierOpenShopPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<SupplierOpenShopResponse> list = supplierOpenShopDao.queryList(request);
        if(CollectionUtils.isEmpty(list)){
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }
        List<SupplierOpenShopResponse> supplierOpenShops = new ArrayList<>();

        supplierOpenShops = list.stream().map(item -> {
            SupplierOpenShopResponse response = new SupplierOpenShopResponse();
            BeanUtils.copyProperties(item, response);
            if(null != businessApply) {
                if (!StringUtils.isEmpty(businessApply.getBusinessAddress())) {
                    response.setBusinessAddress(businessApply.getBusinessAddress());
                }
                if (null != businessApply.getShippingType()) {
                    response.setShippingTypeName(WineryShippingTypeEnum.getMsgByCode(businessApply.getShippingType()));
                }
            }
            response.setProductSelectTypeName(ShopProductSelectTypeEnum.getMsgByCode(response.getProductSelectType()));
            // 平台
            if(StringUtils.isNotBlank(response.getPlatformIds())) {
                List<Integer> platformIds = JSONObject.parseArray(response.getPlatformIds(), Integer.class);
                StringBuilder stringBuilder = new StringBuilder();
                for(Integer id : platformIds){
                    if(id == null){
                        continue;
                    }
                    String name = channelMerchantMap.get(id);
                    stringBuilder.append(" | ").append(name);
                }
                if(stringBuilder.length() > 3){
                    response.setPlatformName(stringBuilder.substring(3, stringBuilder.length()));
                }else{
                    response.setPlatformName(stringBuilder.toString());
                }
            }

            return response;
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(supplierOpenShops)) {
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }

        return CommonPage.copyPageInfo(supplierOpenShopPage, supplierOpenShops);
    }

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<SupplierOpenShopResponse> getListV2(SupplierOpenShopRequest request, PageParamRequest pageParamRequest) {
        //条件查询
        MerchantListRequest merchantListRequest = new MerchantListRequest();
        merchantListRequest.setNotChannelType(3);
        merchantListRequest.setPage(1);
        merchantListRequest.setLimit(9999);
        PageInfo<ChannelMerchantVO>  channelMerchantVOPageInfo = channelMerchantService.merchantListV2(merchantListRequest, false);
        List<ChannelMerchantVO> channelMerchantList = channelMerchantVOPageInfo.getList();
        Map<Integer, String> channelMerchantMap = channelMerchantList.stream().collect(Collectors.toMap(ChannelMerchantVO::getId, ChannelMerchantVO::getChannelName, (e1, e2) -> e2));

        Page<SupplierOpenShop> supplierOpenShopPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<SupplierOpenShopResponse> list = supplierOpenShopDao.queryList(request);
        if(CollectionUtils.isEmpty(list)){
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }

        List<Integer> shopMerIds = list.stream().map(SupplierOpenShopResponse::getShopMerId).collect(Collectors.toList());
        Map<Integer, String> merchantMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(shopMerIds)) {
            LambdaQueryWrapper<ChannelMerchant> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(ChannelMerchant::getId, ChannelMerchant::getChannelName);
            wrapper.in(ChannelMerchant::getId, shopMerIds);

            List<ChannelMerchant> merchantList = channelMerchantDao.selectList(wrapper);
            Map<Integer, String> map = merchantList.stream().collect(Collectors.toMap(ChannelMerchant::getId, ChannelMerchant::getChannelName));
            merchantMap.putAll(map);
        }
        List<Integer> applyIds = list.stream().map(SupplierOpenShopResponse::getApplyId).collect(Collectors.toList());

        LambdaQueryWrapper<BusinessApply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(BusinessApply::getId, applyIds);
        List<BusinessApply> businessApplyList = businessApplyDao.selectList(lambdaQueryWrapper);
        Map<Integer, BusinessApply> businessApplyMap = businessApplyList.stream().collect(Collectors.toMap(BusinessApply::getId, e -> e, (e1, e2) -> e2));

        List<SupplierOpenShopResponse> supplierOpenShops = list.stream().map(item -> {
            SupplierOpenShopResponse response = new SupplierOpenShopResponse();
            BeanUtils.copyProperties(item, response);

            String channelName = merchantMap.get(response.getShopMerId());
            if (StringUtils.isNotEmpty(channelName)) {
                response.setChannelName(channelName);
            }
            BusinessApply apply = businessApplyMap.get(response.getApplyId());
            if(null != apply) {
                if (!StringUtils.isEmpty(apply.getBusinessAddress())) {
                    response.setBusinessAddress(apply.getBusinessAddress());
                }
                if (null != apply.getShippingType()) {
                    response.setShippingTypeName(WineryShippingTypeEnum.getMsgByCode(apply.getShippingType()));
                }
            }
            response.setProductSelectTypeName(ShopProductSelectTypeEnum.getMsgByCode(response.getProductSelectType()));
            // 平台
            if(StringUtils.isNotBlank(response.getPlatformIds())) {
                List<Integer> platformIds = JSONObject.parseArray(response.getPlatformIds(), Integer.class);
                StringBuilder stringBuilder = new StringBuilder();
                for(Integer id : platformIds){
                    if(id == null){
                        continue;
                    }
                    String name = channelMerchantMap.get(id);
                    stringBuilder.append(" | ").append(name);
                }
                if(stringBuilder.length() > 3){
                    response.setPlatformName(stringBuilder.substring(3, stringBuilder.length()));
                }else{
                    response.setPlatformName(stringBuilder.toString());
                }
            }

            return response;
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(supplierOpenShops)) {
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }

        return CommonPage.copyPageInfo(supplierOpenShopPage, supplierOpenShops);
    }

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<SupplierOpenShopResponse> frontList(SupplierOpenShopRequest request, PageParamRequest pageParamRequest) {
        //条件查询
        MerchantListRequest merchantListRequest = new MerchantListRequest();
        merchantListRequest.setNotChannelType(3);
        merchantListRequest.setPage(1);
        merchantListRequest.setLimit(9999);
        PageInfo<ChannelMerchantVO>  channelMerchantVOPageInfo = channelMerchantService.merchantListV2(merchantListRequest, false);
        List<ChannelMerchantVO> channelMerchantList = channelMerchantVOPageInfo.getList();
        Map<Integer, String> channelMerchantMap = channelMerchantList.stream().collect(Collectors.toMap(ChannelMerchantVO::getId, ChannelMerchantVO::getChannelName, (e1, e2) -> e2));

        LambdaQueryWrapper<BusinessApply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(request.getWineryType() == null || request.getWineryType() == 0 || request.getWineryType() == 1){
            lambdaQueryWrapper.ne(BusinessApply::getCountry, "中国大陆")
                    .ne(BusinessApply::getCountry, "中国港澳")
                    .eq(BusinessApply::getApplyType, SupplierTypeEnum.WINERY.getType());
        }else if(request.getWineryType() == 2){
            lambdaQueryWrapper.ne(BusinessApply::getCountry, "中国大陆")
                    .ne(BusinessApply::getCountry, "中国港澳")
                    .eq(BusinessApply::getApplyType, SupplierTypeEnum.VINTNER.getType());
        }else if(request.getWineryType() == 3){
            lambdaQueryWrapper.eq(BusinessApply::getCountry, "中国大陆")
                    .eq(BusinessApply::getApplyType, SupplierTypeEnum.VINTNER.getType());
        }else if(request.getWineryType() == 4){
            lambdaQueryWrapper.eq(BusinessApply::getCountry, "中国港澳")
                    .eq(BusinessApply::getApplyType, SupplierTypeEnum.VINTNER.getType());
        }
        List<BusinessApply> businessApplyList = businessApplyDao.selectList(lambdaQueryWrapper);
        Map<Integer, BusinessApply> businessApplyMap = businessApplyList.stream().collect(Collectors.toMap(BusinessApply::getId, e -> e, (e1, e2) -> e2));

        List<Integer> applyIds = businessApplyList.stream().map(BusinessApply::getId).collect(Collectors.toList());
        request.setApplyIdList(applyIds);
        Page<SupplierOpenShop> supplierOpenShopPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<SupplierOpenShopResponse> list = supplierOpenShopDao.queryList(request);

        if(CollectionUtils.isEmpty(list)){
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }

        List<Integer> shopMerIds = list.stream().map(SupplierOpenShopResponse::getShopMerId).collect(Collectors.toList());
        Map<Integer, String> merchantMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(shopMerIds)) {
            LambdaQueryWrapper<ChannelMerchant> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(ChannelMerchant::getId, ChannelMerchant::getChannelName);
            wrapper.in(ChannelMerchant::getId, shopMerIds);

            List<ChannelMerchant> merchantList = channelMerchantDao.selectList(wrapper);
            Map<Integer, String> map = merchantList.stream().collect(Collectors.toMap(ChannelMerchant::getId, ChannelMerchant::getChannelName));
            merchantMap.putAll(map);
        }

        List<SupplierOpenShopResponse> supplierOpenShops = list.stream().map(item -> {
            SupplierOpenShopResponse response = new SupplierOpenShopResponse();
            BeanUtils.copyProperties(item, response);

            String channelName = merchantMap.get(response.getShopMerId());
            if (StringUtils.isNotEmpty(channelName)) {
                response.setChannelName(channelName);
            }
            BusinessApply apply = businessApplyMap.get(response.getApplyId());
            if(null != apply) {
                if (!StringUtils.isEmpty(apply.getBusinessAddress())) {
                    response.setBusinessAddress(apply.getBusinessAddress());
                }
                if (null != apply.getShippingType()) {
                    response.setShippingTypeName(WineryShippingTypeEnum.getMsgByCode(apply.getShippingType()));
                }
            }
            response.setProductSelectTypeName(ShopProductSelectTypeEnum.getMsgByCode(response.getProductSelectType()));
            // 平台
            if(StringUtils.isNotBlank(response.getPlatformIds())) {
                List<Integer> platformIds = JSONObject.parseArray(response.getPlatformIds(), Integer.class);
                StringBuilder stringBuilder = new StringBuilder();
                for(Integer id : platformIds){
                    if(id == null){
                        continue;
                    }
                    String name = channelMerchantMap.get(id);
                    stringBuilder.append(" | ").append(name);
                }
                if(stringBuilder.length() > 3){
                    response.setPlatformName(stringBuilder.substring(3, stringBuilder.length()));
                }else{
                    response.setPlatformName(stringBuilder.toString());
                }
            }

            return response;
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(supplierOpenShops)) {
            return CommonPage.copyPageInfo(supplierOpenShopPage, new ArrayList<>());
        }

        return CommonPage.copyPageInfo(supplierOpenShopPage, supplierOpenShops);
    }

    @Override
    public boolean updateImgById(SupplierOpenShop supplierOpenShop) {
        return supplierOpenShopDao.updateImgById(supplierOpenShop);
    }

    /**
     * 创建店铺
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createOrUpdate(SupplierOpenShopRequest shopRequest, Integer merId) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        if(null == supplierInfo){
            throw new CrmebException("供应商的商户信息不存在！");
        }
        Integer supplierId = null;
        if(null != supplierInfo.getSupplierId()){
            supplierId = supplierInfo.getSupplierId();
        }
        LambdaQueryWrapper<SupplierOpenShop> queryWrapper = new LambdaQueryWrapper<>();
        SupplierOpenShop existShop = null;
        if (shopRequest.getId() != null && shopRequest.getId() != 0){
            queryWrapper.ne(SupplierOpenShop::getId,shopRequest.getId());
            existShop = this.getById(shopRequest.getId());
        }
        queryWrapper.eq(SupplierOpenShop :: getTitle, shopRequest.getTitle());

        if(null != supplierId) {
            queryWrapper.eq(SupplierOpenShop::getSupplierId, supplierId);
        }
        int isHas = this.count(queryWrapper);
        if(isHas > 0) {
            throw new CrmebException("当前店铺名称已存在！");
        }
        if(existShop != null){
            // 编辑
            // 1 shop
            SupplierOpenShop shop = new SupplierOpenShop();
            BeanUtils.copyProperties(shopRequest, shop);
            shop.setId(shopRequest.getId());
            shop.setSupplierId(supplierId);
            shop.setMerId(supplierInfo.getMerchantId());
            shop.setApplyId(supplierInfo.getApplyId());
            shop.setSupplierName(supplierInfo.getSupplierName());
            if(CollectionUtils.isNotEmpty(shopRequest.getPlatformIdList())) {
                // TODO toString()
                shop.setPlatformIds(shopRequest.getPlatformIdList().toString());
            }
            Integer userId = userService.getUserIdException();
            shop.setCreateUserUid(userId);

            this.updateById(shop);

            // 2 商品
            // 删除原来绑定的商品
            supplierOpenShopProductDao.deleteByShopId(shopRequest.getId());
            // 新增商品
            if(shopRequest.getProductSelectType() != null && shopRequest.getProductSelectType() == 2) {
                List<SupplierOpenShopProduct> shopProductList = new ArrayList<>();
                List<Integer> list = shopRequest.getProductIdList();
                List<Integer> productIdList = list.stream().distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(productIdList)) {
                    for (Integer productId : productIdList) {
                        StoreProduct product = storeProductService.getById(productId);
                        if (null == product) {
                            continue;
                        }
                        SupplierOpenShopProduct shopProduct = new SupplierOpenShopProduct();
                        shopProduct.setShopId(shop.getId());
                        shopProduct.setProductId(productId);
                        shopProduct.setSupplierId(supplierId);
                        shopProduct.setMerId(supplierInfo.getMerchantId());
                        shopProduct.setSupplierName(supplierInfo.getSupplierName());
                        shopProductList.add(shopProduct);
                    }
                }
                supplierOpenShopProductService.saveBatch(shopProductList);
            }

        }else{
            // 新增
            // 1 shop
            SupplierOpenShop shop = new SupplierOpenShop();
            BeanUtils.copyProperties(shopRequest, shop);
            shop.setSupplierId(supplierId);
            shop.setMerId(supplierInfo.getMerchantId());
            shop.setApplyId(supplierInfo.getApplyId());
            shop.setSupplierName(supplierInfo.getSupplierName());
            if(CollectionUtils.isNotEmpty(shopRequest.getPlatformIdList())) {
                // TODO toString()
                shop.setPlatformIds(shopRequest.getPlatformIdList().toString());
            }
            Integer userId = userService.getUserIdException();
            shop.setCreateUserUid(userId);

            this.save(shop);

            // 2 商品
            // 新增商品
            if(shopRequest.getProductSelectType() != null && shopRequest.getProductSelectType() == 2) {
                List<SupplierOpenShopProduct> shopProductList = new ArrayList<>();
                List<Integer> list = shopRequest.getProductIdList();
                List<Integer> productIdList = list.stream().distinct().collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(productIdList)) {
                    for (Integer productId : productIdList) {
                        StoreProduct product = storeProductService.getById(productId);
                        if (null == product) {
                            continue;
                        }
                        SupplierOpenShopProduct shopProduct = new SupplierOpenShopProduct();
                        shopProduct.setShopId(shop.getId());
                        shopProduct.setProductId(productId);
                        shopProduct.setSupplierId(supplierId);
                        shopProduct.setMerId(supplierInfo.getMerchantId());
                        shopProduct.setSupplierName(supplierInfo.getSupplierName());
                        shopProductList.add(shopProduct);
                    }
                }
                supplierOpenShopProductService.saveBatch(shopProductList);
            }
        }
        return true;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public SupplierOpenShopResponse shopDetail(Integer id, Integer merId) {
        if (id == null || id == 0) {
            throw new CrmebException("参数id错误！");
        }
        SupplierOpenShopResponse shopResponse = new SupplierOpenShopResponse();
        SupplierOpenShop shop = this.getById(id);
        BeanUtils.copyProperties(shop, shopResponse);
        List<SupplierOpenShopProduct> shopProductList = supplierOpenShopProductService.list(Wrappers.<SupplierOpenShopProduct>lambdaQuery()
                .eq(SupplierOpenShopProduct::getShopId, id));
        List<Integer> productIdList = shopProductList.stream().map(SupplierOpenShopProduct::getProductId).distinct().collect(Collectors.toList());
        shopResponse.setProductIdList(productIdList);
        if(StringUtils.isNotBlank(shopResponse.getPlatformIds())){
//            shopResponse.setPlatformIdList(CrmebUtil.stringToArray(shopResponse.getPlatformIds()));
            shopResponse.setPlatformIdList(JSONObject.parseArray(shopResponse.getPlatformIds(), Integer.class));
        }
        if(CollectionUtils.isNotEmpty(productIdList)){
            SupplierStoreProductSearchRequest searchRequest = new SupplierStoreProductSearchRequest();
            searchRequest.setProductIds(productIdList);
            searchRequest.setType(1);
            searchRequest.setIsImg(false);
            searchRequest.setPage(1);
            searchRequest.setLimit(productIdList.size());
            PageInfo<StoreProductResponse> pageInfo = supplierStoreProductService.supplierProductList(searchRequest,merId);
            List<StoreProductResponse> productResponses = pageInfo.getList();
            shopResponse.setProductList(productResponses);
        }else{
            shopResponse.setProductList(new ArrayList<>());
        }
        return shopResponse;
    }

    /**
     * 详情
     *
     * @param
     * @return
     */
    @Override
    public PageInfo<StoreProductResponse> supplierProductList(SupplierStoreProductSearchRequest searchRequest, Integer supplierId){
        Integer id = searchRequest.getShopId();
        if (id == null || id == 0) {
            throw new CrmebException("参数id错误！");
        }
        List<SupplierOpenShopProduct> shopProductList = supplierOpenShopProductService.list(Wrappers.<SupplierOpenShopProduct>lambdaQuery()
                .eq(SupplierOpenShopProduct::getShopId, id));
        List<Integer> productIdList = shopProductList.stream().map(SupplierOpenShopProduct::getProductId).distinct().collect(Collectors.toList());

        Page<StoreProduct> storeProductPage = PageHelper.startPage(searchRequest.getPage(), searchRequest.getLimit());
        if (CollectionUtils.isEmpty(productIdList)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        searchRequest.setProductIds(productIdList);
        searchRequest.setType(1);
        searchRequest.setIsImg(false);
        PageInfo<StoreProductResponse> pageInfo = supplierStoreProductService.supplierProductList(searchRequest,supplierId);

        return pageInfo;
    }

    @Override
    public boolean deleteShopById(Integer id) {
        supplierOpenShopDao.updateDelById(id);
        // 删除原来绑定的商品
        supplierOpenShopProductDao.updateDelByShopId(id);
        return true;
    }

    /**
     * // 新增渠道商户时，增加一个shopId，并根据这个shopId查询一键开店铺表，在表中增加字段 shop_mer_id,对应分表数据
     *         // 在使用小程序端查询一键开店商品时，根据shop_id 查询 shop_mer_id，并找到对应的分表，取出分表里的数据
     *         // 更新分表：
     *         //        1 更新一键开店
     *         //        2 供应桑上架商品
     *         //        3 新增商户、修改商户
     *
     */
    @Override
    public CommonPage<ProductResponse> frontProductList(ProductRequest request, PageParamRequest pageParamRequest) {
        String keyword = request.getKeyword();
        Integer merId = request.getMerId();
        Integer shopId = request.getShopId();
        SupplierOpenShop openShop = this.getById(shopId);
        if(null == openShop){
            throw new CrmebException("供应商一键开店的店铺不存在。");
        }
        if(null == openShop.getShopMerId() || 0 == openShop.getShopMerId()){
            throw new CrmebException("供应商一键开店的商品不存在。");
        }
        Integer shopMerId = openShop.getShopMerId();

        Integer productSelectType = openShop.getProductSelectType();
        IndexStoreProductSearchRequest indexStoreProductSearchRequest = new IndexStoreProductSearchRequest();
        BeanUtils.copyProperties(request, indexStoreProductSearchRequest);
        indexStoreProductSearchRequest.setMerId(shopMerId);
        if(null != productSelectType && productSelectType == 2) {
            List<SupplierOpenShopProduct> shopProductList = supplierOpenShopProductService.list(Wrappers.<SupplierOpenShopProduct>lambdaQuery()
                    .eq(SupplierOpenShopProduct::getShopId, shopId));
            List<Integer> productIdList = shopProductList.stream().map(SupplierOpenShopProduct::getProductId).distinct().collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(productIdList)) {
                indexStoreProductSearchRequest.setProductIdList(productIdList);
            }

        }else {
            Integer supplierId = openShop.getSupplierId();
            if(null != supplierId && 0 != supplierId) {
                indexStoreProductSearchRequest.setSuppliersIds(String.valueOf(supplierId));
            }
        }
        indexStoreProductSearchRequest.setType(1);
        indexStoreProductSearchRequest.setKeywords(keyword);
        if (null != request.getNews()) {
            indexStoreProductSearchRequest.setIsNew(request.getNews());
        }
        indexStoreProductSearchRequest.setShowIds(Collections.singletonList(0));
        indexStoreProductSearchRequest.setIsShow(1);
        CommonPage<ProductResponse> response = productService.getShopProduct(indexStoreProductSearchRequest, pageParamRequest);

        return response;
    }

}